﻿using System.Net;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using eLibrary.Constant;

using SQuicConnection = System.Net.Quic.QuicConnection;

namespace Letter.Net.Quic;

sealed class QuicClient : AQuicHost<QuicClientTransportOptions, QuicClientFeatureOptions>, IQuicClient
{
    public QuicClient(string name) : base(name)
    {
    }

    [RequiresPreviewFeatures]
    private SQuicConnection connection;
    private EndPoint bindEndPoint;
    private int isStop = Booleans.FALSE;
    
    public override EndPoint BindEndPoint
    {
        get { return this.bindEndPoint; }
    }

    public override void Build()
    {
        base.Build();
    }

    [RequiresPreviewFeatures]
    public override async Task ConnectAsync(EndPoint endPoint)
    {
        this.connection = await SQuicConnection.ConnectAsync(null);
        this.bindEndPoint = this.connection.LocalEndPoint;
        var conn = new QuicConnection(connection);
    }

    [RequiresPreviewFeatures]
    public override async Task StopAsync()
    {
        if (Interlocked.CompareExchange(ref this.isStop, Booleans.TRUE, Booleans.FALSE) == Booleans.FALSE)
        {
            try
            {
                await this.connection.CloseAsync(QuicDefinitionError.CLOSE_ERROR);
                await this.connection.DisposeAsync();
            }
            catch
            {
            }
            finally
            {
                
            }
        }
    }
}